package com.itheima.servlet;

import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Dish;
import com.itheima.uilts.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addDish")
public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        1. 解决post请求乱码问题
        response.setCharacterEncoding("utf-8");
//        2. 获取请求数据
        String name = request.getParameter("name");
        Double price = Double.valueOf(request.getParameter("price"));
        String description = request.getParameter("description");

//        3. 将获取到的浏览器提交的数据封装到实体类对象中

        Dish dish=new Dish();
        dish.setName(name);
        dish.setPrice(price);
        dish.setDescription(description);
//        4. 调用mapper方法进行数据添加操作

        SqlSessionFactory sqlSessionFactory=SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession=sqlSessionFactory.openSession();
        DishMapper mapper = sqlSession.getMapper(DishMapper.class);
//        5. 提交事务
        mapper.add(dish);
        sqlSession.commit();
//        6. 应添加数据成功标识
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("添加成功");
    }
}